<?php

namespace Trawind\Basics\Traits;

use Trawind\Helpers\LogHelper;
use Trawind\Helpers\UserHelper;
use Trawind\Basics\Observers\TrawindObserver;
use Trawind\Rocketmq\Helpers\RocketMQHelper;

/**
 * Trait AutoMaintainOperator
 *
 * @property-read   $businessType
 * @property-read   $maintainUser
 * @property-read   $writeLogSwitch
 */
trait AutoMaintainOperator
{

    use HasEnumerate;

    public static function boot()
    {
        parent::boot();
        static::observe(TrawindObserver::class);
    }


    public function creatingHandle($model)
    {
        foreach (static::fillDefaultValue() as $field => $value) {
            $model->$field = $model->$field ?? $value;
        }
    }


    public function savedHandle($model)
    {
        $this->pushToNsMq($model, $model->wasRecentlyCreated ? 'store' : 'update');
        $this->writeLog($model->id);
    }


    public function deletedHandle($model)
    {
        $this->writeLog($model->id);
        $this->pushToNsMq($model, 'destroy');
    }


    public static function fillDefaultValue()
    {
        return [];
    }


    public function fillOperateUser($model, $isUpdate = false)
    {
        if ($this->maintainUser ?? true) {
            $userId = UserHelper::userId(0);
            $isUpdate or $model->created_id = $userId;
            $model->updated_id = $userId;
        }
    }


    public function writeLog($id)
    {
        $writeLogSwitch = $this->writeLogSwitch ?? true;
        $businessType = $this->businessType ?? null;
        if ($writeLogSwitch && !is_null($businessType)) {
            LogHelper::record($id, app(static::class)->businessType);
        }
    }


    /**
     * @param          $model
     * @param  string  $scene
     */
    protected function pushToNsMq($model, string $scene)
    {
        if (property_exists(static::class, 'nsMQ') && $this->nsMQ) {
            $mq = $this->nsMQ[$scene];
            $isCan = true;
            if (isset($mq['condition'])) {
                if ($mq['condition'][1] == 'neq') {
                    $isCan = $model[$mq['condition'][0]] != $mq['condition'][2];
                }
            }
            if ($isCan) {
                if (isset($mq['topic'])) {
                    RocketMQHelper::factory($mq['job'])
                        ->dispatch([
                            'id' => $model['id'],
                            'external_id' => $model['external_id'],
                        ])
                        ->onQueue($mq['topic']);
                } else {
                    $mq['job']::dispatch([
                        'id' => $model['id'],
                        'external_id' => $model['external_id'],
                    ]);
                }
            }
        }
    }


    public function getTreeTopNode(): array
    {
        $defaultTopNode = [
            'id' => 0,
            'parent_id' => '-1',
            'name' => ___('please_choose')
        ];
        method_exists(static::class, 'treeTopNode') and $defaultTopNode = array_merge($defaultTopNode,
            $this->treeTopNode());
        return $defaultTopNode;
    }

}
